package com.wf.smartcomm.server.serviceImpl;

import javax.annotation.Resource;

import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.wf.smartcomm.server.bean.Announcement;
import com.wf.smartcomm.server.bean.User;
import com.wf.smartcomm.server.bean.Village;
import com.wf.smartcomm.server.model.Page;
import com.wf.smartcomm.server.service.AnnounceService;
import com.wf.smartcomm.server.util.IdUtils;
import com.wf.smartcomm.server.util.PageUtils;

@Service
@Transactional
public class AnnounceServiceImpl implements AnnounceService {

	@Resource
	private SessionFactory factory;
	
	@Override
	public void save(Announcement announce) {
		announce.setObjectId(IdUtils.uuid());
		announce.setCreatedAt(String.valueOf(System.currentTimeMillis()));
		announce.setUpdateAt(announce.getCreatedAt());
		factory.getCurrentSession().persist(announce);
	}

	@Override
	@Transactional(propagation=Propagation.NOT_SUPPORTED)
	public void list(Village village, Page page) {
		Query query = factory.getCurrentSession().createQuery("select count(*) from Announcement where village=:village");
		query.setParameter("village", village);
		Long counts = (Long) query.uniqueResult();
		page.setTotalCount(counts.intValue());
		query = factory.getCurrentSession().createQuery("from Announcement where village=:village order by updateAt desc");
		query.setParameter("village", village);
		query.setFirstResult(page.getBeginIndex());
		query.setMaxResults(page.getPageSize());
		page.setDataList(query.list());
	}

	@Override
	@Transactional(propagation=Propagation.NOT_SUPPORTED)
	public Announcement get(String id) {
		Query query = factory.getCurrentSession().createQuery("from Announcement where objectId =:id");
		query.setParameter("id", id);
		return (Announcement) query.uniqueResult();
	}

	@Override
	public void update(Announcement announce) {
		announce.setUpdateAt(String.valueOf(System.currentTimeMillis()));
		factory.getCurrentSession().update(announce);
	}

	@Override
	public void delete(Announcement announce) {
		factory.getCurrentSession().delete(announce);
	}

	@Override
	public Page list(User user, Page page) {
		Query query = factory.getCurrentSession().createQuery("select count(*) from Announcement where village=:village");
		query.setParameter("village", user.getLoginVillage());
		Long counts = (Long) query.uniqueResult();
		Page p = PageUtils.createPage(page, counts.intValue());
		query =  factory.getCurrentSession().createQuery("from Announcement where village=:village order by updateAt desc");
		query.setParameter("village", user.getLoginVillage());
		query.setFirstResult(p.getBeginIndex());
		query.setMaxResults(15);
		p.setDataList(query.list());
		return p;
	}
}
